# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Pro数据接口
Created on 2017/07/01
@author: polo,Jimmy
@group : https://waditu.com
"""

import pandas as pd
import json
from functools import partial
import requests


class DataApi:

    __token = ''
    __http_url = 'http://api.waditu.com'

    def __init__(self, token, timeout=30):
        """
        Parameters
        ----------
        token: str
            API接口TOKEN，用于用户认证
        """
        self.__token = token
        self.__timeout = timeout

    def query(self, api_name, fields='', **kwargs):
        req_params = {
            'api_name': api_name,
            'token': self.__token,
            'params': kwargs,
            'fields': fields
        }

        res = requests.post(self.__http_url, json=req_params, timeout=self.__timeout)
        if res:
            result = json.loads(res.text)
            if result['code'] != 0:
                raise Exception(result['msg'])
            data = result['data']
            columns = data['fields']
            items = data['items']
            return pd.DataFrame(items, columns=columns)
        else:
            return pd.DataFrame()

    def __getattr__(self, name):
        return partial(self.query, name)

    def find_crossovers(df):
        df = df.sort_values('trade_date')
        df['ma5_gt_ma10'] = df['ma5'] > df['ma10']
        df['crossover'] = df['ma5_gt_ma10'].astype(int).diff() == 1  # Find where it changes from False to True

        if df['crossover'].any():
            return df[df['crossover']].iloc[-1]  # Return most recent crossover
        else:
            return None

    if 'daily_data' in locals():
        crossovers = daily_data.groupby('ts_code').apply(find_crossovers).dropna()

        print("\nStocks with MA5 crossing above MA10:")
        if not crossovers.empty:
            print(crossovers[['ts_code', 'trade_date', 'close', 'ma5', 'ma10']])
        else:
            print("No crossover stocks found")